﻿using AForge.Video.DirectShow;
using Common;
using FaceAppClient.Baidu.FaceAPI;
using FaceAppClient.FaceModel;
using System;
using System.Collections;
using System.Drawing;
using System.Drawing.Imaging;
using System.Windows.Forms;


namespace FaceAppClient
{
    public partial class Form1 : Form
    {
        private FilterInfoCollection videoDevices;
        private VideoCaptureDevice videoSource;
        public int selectedDeviceIndex = 0;
        private static DetectModel dm;
        private static IdentifyModel im;
        private static AddModel am;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            ShowMsg.showMsg(listBox_Info, "system start ... ok!");
            videoDevices = GetDevices();
            if (videoDevices != null)
            {
                selectedDeviceIndex = 0;//一般取默认摄像头，即枚举中的第一个
                videoSource = new VideoCaptureDevice(videoDevices[selectedDeviceIndex].MonikerString);//连接摄像头。
                videoSource.VideoResolution = videoSource.VideoCapabilities[selectedDeviceIndex];
                videoSourcePlayer1.VideoSource = videoSource;
                ShowMsg.showMsg(listBox_Info, "camare is standing by ...");
                videoSourcePlayer1.Start();
                ShowMsg.showMsg(listBox_Info, "camera start ... ok!");
            }
            else
            {
                btn_Start.Enabled = false;
                btn_Close.Enabled = false;
                btn_Take.Enabled = false;

            }
        }

        public FilterInfoCollection GetDevices()
        {
            try
            {
                ShowMsg.showMsg(listBox_Info, "searching video devices ...");
                //枚举所有视频输入设备  
                videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
                if (videoDevices.Count != 0)
                {
                    ShowMsg.showMsg(listBox_Info, "devices detected!");
                    return videoDevices;
                }
                else
                    return null;
            }
            catch (Exception ex)
            {
                ShowMsg.showMsg(listBox_Info, "devices not detected!：" + ex.Message);
                return null;
            }
        }
        private void button2_Click(object sender, EventArgs e)
        {
            if (videoSource == null)
            {
                ShowMsg.showMsg(listBox_Info, "VideoSource is not ready!");
                return;
            }
            Bitmap bitmap = videoSourcePlayer1.GetCurrentVideoFrame();
            string facePath = string.Format(@"D:\Face\{0}", DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss-ff") + ".jpg");
            bitmap.Save(facePath, ImageFormat.Jpeg);
            bitmap.Dispose();
            ShowMsg.showMsg(listBox_Info, "take photo ... ok!");
            ShowMsg.showMsg(listBox_Info, "Face Checking ...");
            FaceOperation.imagePath = facePath;
            FaceOperation.base64 = imageToBase64(facePath);
            string jsonStr = FaceOperation.FaceDetect();
            dm = Newtonsoft.Json.JsonConvert.DeserializeObject<DetectModel>(jsonStr);
            int ret = FaceOperation.CheckFace(dm);//检测图片是否符合要求
            if (ret > 0)
            {
                ShowMsg.showMsg(listBox_Info, checkMsg(ret));
            }
            else
            {
                ShowMsg.showMsg(listBox_Info, "Face Check successfully!");
                System.Threading.Thread.Sleep(3000);
                ShowMsg.showMsg(listBox_Info, "Searching the face");
                string JsonIdentify = FaceOperation.FaceIdentify();
                im = Newtonsoft.Json.JsonConvert.DeserializeObject<IdentifyModel>(JsonIdentify);
                bool flag = false;
                foreach (var score in im.result[0].scores)
                {
                    if (score > 80)
                    {
                        flag = true;                        
                        break;
                    }
                    else
                    {
                        continue;
                    }
                }
                if (!flag)
                {
                    ShowMsg.showMsg(listBox_Info, "Face does not exist!");
                    if (MessageBox.Show("人脸未找到，是否注册?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                    {
                        string JsonAdd = FaceOperation.FaceAdd();
                        am = Newtonsoft.Json.JsonConvert.DeserializeObject<AddModel>(JsonAdd);
                        if (am.error_code == 0)
                            ShowMsg.showMsg(listBox_Info, "人脸注册成功");
                    }
                }
                else
                {
                    ShowMsg.showMsg(listBox_Info, "Searching face successfully!");
                    ShowMsg.showMsg(listBox_Info, "Face similarity:" + im.result[0].scores[0] + "%");
                }
            }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (videoSource != null)
                videoSource.Stop();
            if(videoSourcePlayer1!=null)
                videoSourcePlayer1.Stop();
        }

        private void btn_Close_Click(object sender, EventArgs e)
        {
            if(videoSource != null)
                videoSource.Stop();
            videoSource = null;
            videoSourcePlayer1.Stop();
            ShowMsg.showMsg(listBox_Info, "camera stop ... ok!");
        }

        private void btn_Start_Click(object sender, EventArgs e)
        {
            videoSource = new VideoCaptureDevice(videoDevices[selectedDeviceIndex].MonikerString);//连接摄像头。
            videoSource.VideoResolution = videoSource.VideoCapabilities[selectedDeviceIndex];
            videoSourcePlayer1.VideoSource = videoSource;
            videoSourcePlayer1.Start();
            ShowMsg.showMsg(listBox_Info, "camera start ... ok!");
        }

        private string imageToBase64(string ImagePath)
        {
            string base64 = FileUtils.getFileBase64(ImagePath);
            return base64;
        }

        private void btn_beauty_Click(object sender, EventArgs e)
        {
            if (dm != null)
            {
                var ret = dm.result[0];
                string info = string.Format("年龄:{0}\n颜值:{1}\n人种:{2}\n性别:{3}\n眼镜:{4}\n表情:{5}\n", ret.age, ret.beauty, ret.race, ret.gender, ret.glasses == 0 ? "无" : "有", ret.expression == 0 ? "不笑" : "笑了");
                MessageBox.Show(info);
            }
        }

        private string checkMsg(int ret)
        {
            string info = "";
            switch (ret)
            {
                case 1:
                    info = "左眼遮挡";
                    break;
                case 2:
                    info = "右眼遮挡";
                    break;
                case 3:
                    info = "鼻子遮挡";
                    break;
                case 4:
                    info = "嘴巴遮挡";
                    break;
                case 5:
                    info = "左脸颊遮挡";
                    break;
                case 6:
                    info = "右脸颊遮挡";
                    break;
                case 7:
                    info = "下巴颏遮挡";
                    break;
                case 8:
                    info = "图片模糊，请重拍";
                    break;
                case 9:
                    info = "图像歪斜严重，请摆正姿势后重拍";
                    break;
                case 10:
                    info = "人脸长款太小，请靠近摄像头后重拍";
                    break;
            }
            return info;            
        }

        private void btn_test_Click(object sender, EventArgs e)
        {
            FaceOperation.imagePath = @"D:\Face\2017-12-20-16-39-45-44.jpg";
            FaceOperation.base64 = imageToBase64(@"D:\Face\2017-12-20-16-39-45-44.jpg");
            string JsonIdentify = FaceOperation.FaceIdentify();
            im = Newtonsoft.Json.JsonConvert.DeserializeObject<IdentifyModel>(JsonIdentify);
            bool flag = false;
            foreach (var score in im.result[0].scores)
            {
                if (score > 80)
                {
                    flag = true;
                    break;
                }
                else
                {
                    continue;
                }
            }
            if (!flag)
            {
                ShowMsg.showMsg(listBox_Info, "Face does not exist!");
                if (MessageBox.Show("人脸未找到，是否注册?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                {
                    string JsonAdd = FaceOperation.FaceAdd();
                    am = Newtonsoft.Json.JsonConvert.DeserializeObject<AddModel>(JsonAdd);
                    if (am.error_code == 0)
                        ShowMsg.showMsg(listBox_Info, "人脸注册成功");
                }
            }
            else
            {
                ShowMsg.showMsg(listBox_Info, "Searching face successfully!");
                ShowMsg.showMsg(listBox_Info, "Face similarity:" + im.result[0].scores[0]+"%");
            }
        }
    }
}
